<template>
  <div class="device-detail-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>设备详情</span>
          <el-button 
            type="primary" 
            @click="handleBack"
          >
            返回列表
          </el-button>
        </div>
      </template>
      
      <!-- 设备基本信息 -->
      <div v-if="!loading && device" class="device-info">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="设备名称">{{ device.name }}</el-descriptions-item>
          <el-descriptions-item label="设备编号">{{ device.deviceNumber }}</el-descriptions-item>
          <el-descriptions-item label="设备类型">{{ device.type }}</el-descriptions-item>
          <el-descriptions-item label="设备描述">{{ device.description || '-' }}</el-descriptions-item>
          <el-descriptions-item label="设备状态">
            <el-tag :type="device.status === 'online' ? 'success' : 'danger'">
              {{ device.status === 'online' ? '在线' : '离线' }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <!-- 地理位置展示（高德地图） -->
        <div class="map-section" v-if="hasLocation">
          <h3>设备位置</h3>
          <div ref="mapContainer" class="map-container" style="width: 100%; height: 400px;"></div>
        </div>
        
        <!-- 视频播放区域 -->
        <div class="video-section" v-if="videoUrl">
          <h3>设备视频</h3>
          <video 
            :src="videoUrl" 
            controls 
            autoplay 
            muted 
            class="video-player" 
            style="width: 100%; height: auto; max-height: 400px;"
          >
            您的浏览器不支持视频播放
          </video>
        </div>
        
        <!-- 设备属性表格 -->
        <div class="properties-section" v-if="deviceProperties.length > 0">
          <h3>设备属性</h3>
          <el-table :data="deviceProperties" style="width: 100%">
            <el-table-column prop="name" label="属性名称" width="180" />
            <el-table-column prop="identifier" label="属性标识" width="120" />
            <el-table-column label="属性值">
              <template #default="scope">
                <!-- 布尔类型属性使用开关 -->
                <el-switch
                  v-if="scope.row.data_type === 'bool' && scope.row.access_mode === '读写'"
                  v-model="boolProperties[scope.row.identifier]"
                  active-text="开启"
                  inactive-text="关闭"
                  @change="handleBoolChange(scope.row.identifier, boolProperties[scope.row.identifier])"
                />
                <!-- cmd属性使用字符串输入框 -->
                <el-input
                  v-else-if="scope.row.access_mode === '读写' && scope.row.identifier === 'cmd'"
                  v-model="editValues[scope.row.identifier]"
                  @change="handleStringChange(scope.row.identifier, editValues[scope.row.identifier])"
                  style="width: 150px;"
                />
                <!-- 数值类型属性（如上报频率、翻转圈数）使用数字输入框 -->
                <el-input-number
                  v-else-if="scope.row.access_mode === '读写' && ['frequency', 'fz_count',  'uid'].includes(scope.row.identifier)"
                  v-model="editValues[scope.row.identifier]"
                  :min="0"
                  :step="1"
                  @change="handleNumberChange(scope.row.identifier, editValues[scope.row.identifier])"
                  style="width: 150px;"
                />
                <!-- 其他类型属性显示值 -->
                <span v-else>{{ formatPropertyValue(scope.row) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="访问模式" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.access_mode === '读写' ? 'success' : 'info'" size="small">
                  {{ scope.row.access_mode }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="更新时间" width="180">
              <template #default="scope">
                {{ formatTimestamp(scope.row.time) }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 设备控制 -->
        <div class="control-section">
          <h3>设备控制</h3>
          <el-form :model="commandForm" label-width="100px">
            <el-form-item label="命令">
              <el-select v-model="commandForm.key" placeholder="请选择命令">
                <el-option label="主码流推送地址" value="SERVER_IP" />
                <el-option label="子码流推送地址" value="SERVER_IP_SMALL" />
                <el-option label="主码流推送端口" value="RTP_PORT" />
                <el-option label="子码流推送端口" value="RTP_PORT_SMALL" />                
                <el-option label="主码流编码类型" value="CODEC_TYPE" />
                <el-option label="子码流编码类型" value="CODEC_TYPE_SMALL" />
                <el-option label="主码流分辨率" value="CHANNEL0_PIC" />
                <el-option label="子码流分辨率" value="CHANNEL1_PIC" />
                <el-option label="WIFI模式" value="WIFI_MODE" />
                <el-option label="设备IP地址" value="WIFI_IP" />
              </el-select>
            </el-form-item>
            <el-form-item label="参数">
              <el-input v-if="commandForm.key == 'SERVER_IP' || commandForm.key == 'SERVER_IP_SMALL' || commandForm.key == 'WIFI_IP'" v-model="commandForm.value" placeholder="请输入IP地址" />
              <el-input v-else-if="commandForm.key == 'RTP_PORT' || commandForm.key == 'RTP_PORT_SMALL'" v-model="commandForm.value" placeholder="请输入端口号" />
              <el-select v-else-if="commandForm.key == 'CODEC_TYPE' || commandForm.key == 'CODEC_TYPE_SMALL'" v-model="commandForm.value" placeholder="请选择编码类型">
                <el-option label="H264" value="H264" />
                <el-option label="H265" value="H265" />
              </el-select>
              <el-select v-else-if="commandForm.key == 'CHANNEL0_PIC' || commandForm.key == 'CHANNEL1_PIC'" v-model="commandForm.value" placeholder="请选择分辨率">
                <el-option label="PIC_360P" value="PIC_360P" />
                <el-option label="PIC_D1_PAL" value="PIC_D1_PAL" />
                <el-option label="PIC_D1_NTSC" value="PIC_D1_NTSC" />
                <el-option label="PIC_960H" value="PIC_960H" />
                <el-option label="PIC_720P" value="PIC_720P" />
                <el-option label="PIC_1080P" value="PIC_1080P" />
                <el-option label="PIC_480P" value="PIC_480P" />
                <el-option label="PIC_576P" value="PIC_576P" />
                <el-option label="PIC_800X600" value="PIC_800X600" />
                <el-option label="PIC_1024X768" value="PIC_1024X768" />
                <el-option label="PIC_1280X1024" value="PIC_1280X1024" />
                <el-option label="PIC_1366X768" value="PIC_1366X768" />
                <el-option label="PIC_1440X900" value="PIC_1440X900" />
                <el-option label="PIC_1280X800" value="PIC_1280X800" />
                <el-option label="PIC_1600X1200" value="PIC_1600X1200" />
                <el-option label="PIC_1680X1050" value="PIC_1680X1050" />
                <el-option label="PIC_1920X1200" value="PIC_1920X1200" />
                <el-option label="PIC_640X480" value="PIC_640X480" />
                <el-option label="PIC_1920X2160" value="PIC_1920X2160" />
                <el-option label="PIC_2304X1296" value="PIC_2304X1296" />
                <el-option label="PIC_2560X1440" value="PIC_2560X1440" />
                <el-option label="PIC_2592X1520" value="PIC_2592X1520" />
                <el-option label="PIC_2688X1520" value="PIC_2688X1520" />
                <el-option label="PIC_2592X1944" value="PIC_2592X1944" />
                <el-option label="PIC_3840X2160" value="PIC_3840X2160" />
                <el-option label="PIC_4096X2160" value="PIC_4096X2160" />
                <el-option label="PIC_3000X3000" value="PIC_3000X3000" />
                <el-option label="PIC_4000X3000" value="PIC_4000X3000" />
                <el-option label="PIC_6080X2800" value="PIC_6080X2800" />
                <el-option label="PIC_7680X4320" value="PIC_7680X4320" />
                <el-option label="PIC_3840X8640" value="PIC_3840X8640" />
                <el-option label="PIC_2880X1620" value="PIC_2880X1620" /> 
                <el-option label="PIC_2560X1600" value="PIC_2560X1600" />
              </el-select>
              <el-select v-else-if="commandForm.key == 'WIFI_MODE'" v-model="commandForm.value" placeholder="请选择WIFI模式">
                <el-option label="广播" value="BROADCAST" />
                <el-option label="普通" value="NORMAL" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="executeCommand" :loading="executingCommand">
                执行命令
              </el-button>
              <el-button type="danger" @click="fota" :loading="executingCommand">
                空中升级
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      
      <!-- 加载中 -->
      <div v-else-if="loading" class="loading-state" v-loading="loading" element-loading-text="加载设备信息中...">
        <div style="height: 200px;"></div>
      </div>
      
      <!-- 设备不存在 -->
      <div v-else class="error-state">
        <el-empty description="设备不存在或已被删除" />
        <el-button type="primary" @click="handleBack" style="margin-top: 20px">
          返回列表
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onUnmounted, watch, inject, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { deviceApi } from '../services/api'
import { ElMessage } from 'element-plus'

export default {
  name: 'DeviceDetail',
  props: {
    id: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const router = useRouter()
    const route = useRoute()
    const device = ref(null)
    const deviceProperties = ref([])
    const loading = ref(true)
    const executingCommand = ref(false)
    const videoUrl = ref('')
    const mapContainer = ref(null)
    const boolProperties = reactive({})
    const editValues = reactive({})
    const locationData = ref({
      lat: null,
      lng: null
    })
    
    // 存储地图相关实例
    const mapInstance = ref(null)
    const markerInstance = ref(null)
    const infoWindowInstance = ref(null)
    const eventSource = ref(null)
    const isSubscribed = ref(false)
    
    const commandForm = reactive({
      key: '',
      value: ''
    })
    
    // 是否有有效的地理位置数据
    const hasLocation = ref(false)
    
    // 加载设备详情
    const loadDeviceDetail = async () => {
      let deviceId = props.id || route.params.id
      if (!deviceId) {
        loading.value = false
        return
      }
      
      // 确保deviceId是字符串类型，避免类型不匹配导致的查找失败
      deviceId = String(deviceId)
      
      try {
        loading.value = true
        // 尝试两种方式获取设备详情：1. 直接从用户设备列表获取，2. 从所有设备列表获取
        let response, devices, foundDevice = null
        
        // 方式1: 从用户设备列表获取（更高效且权限更准确）
        const userStore = inject('userStore')
        const userId = userStore?.currentUser?.value?.id
        if (userId) {
          try {
            response = await deviceApi.getUserDevices(userId)
            devices = response.data || []
            foundDevice = devices.find(d => String(d.id) === deviceId)
          } catch (err) {
            console.log('获取用户设备列表失败，尝试从所有设备获取:', err)
          }
        }
        
        // 方式2: 如果方式1失败，从所有设备列表获取
        if (!foundDevice) {
          response = await deviceApi.getAllDevices()
          devices = response.data || []
          foundDevice = devices.find(d => String(d.id) === deviceId)
        }
        
        device.value = foundDevice
        
        // 加载设备属性
        if (device.value) {
          await loadDeviceProperties(deviceId)
        }
      } catch (error) {
        console.error('加载设备详情失败:', error)
        ElMessage.error('加载设备详情失败')
      } finally {
        loading.value = false
      }
    }
    
    // 加载设备属性
    const loadDeviceProperties = async (deviceId) => {
      try {
        const response = await deviceApi.getDeviceProperties(deviceId)
        
        // 解析properties对象为数组格式
        if (response && response.properties) {
          const propsArray = Object.values(response.properties).map(prop => {
            // 对于布尔类型属性，初始化到boolProperties中
            if (prop.data_type === 'bool' && prop.value !== null) {
              boolProperties[prop.identifier] = prop.value === 'true' || prop.value === true
            }
            // 确保属性设置为可读写模式
            if (['cmd', 'frequency', 'fz_count','uid'].includes(prop.identifier)) {
              prop.access_mode = '读写'
              // 初始化到editValues中
              if (prop.value !== null) {
                if (prop.identifier === 'cmd') {
                  // cmd属性保持字符串类型
                  editValues[prop.identifier] = String(prop.value)
                } else {
                  // 数值属性转换为数字类型
                  editValues[prop.identifier] = Number(prop.value)
                }
              }
            }
            return prop
          })
          deviceProperties.value = propsArray
          
          // 提取经纬度数据
          extractLocationData(response.properties)
          
          // 设置视频URL
          videoUrl.value = response.videoUrl || ''
          
          // 使用定时器和nextTick确保DOM已完全渲染后再初始化地图
          if (hasLocation.value) {
            nextTick(() => {
              if (mapContainer.value) {
                initMap()
              } else {
                // 如果首次nextTick检查失败，尝试延迟再检查一次
                setTimeout(() => {
                  nextTick(() => {
                    if (mapContainer.value) {
                      initMap()
                    } else {
                      console.warn('地图容器未找到，无法初始化地图')
                    }
                  })
                }, 300)
              }
            })
          }
        }
      } catch (error) {
        console.error('加载设备属性失败:', error)
        ElMessage.error('加载设备属性失败')
      }
    }
    
    // 提取地理位置数据
    const extractLocationData = (properties) => {
      if (properties.lat && properties.lng && 
          properties.lat.value !== null && properties.lng.value !== null) {
        const newLat = parseFloat(properties.lat.value)
        const newLng = parseFloat(properties.lng.value)
        
        // 检查经纬度是否发生变化
        const locationChanged = locationData.value.lat !== newLat || locationData.value.lng !== newLng
        
        // 更新位置数据
        locationData.value = {
          lat: newLat,
          lng: newLng
        }
        hasLocation.value = true
        
        // 如果经纬度发生变化且地图已初始化，更新地图位置
        if (locationChanged && mapInstance.value) {
          updateMapLocation(newLng, newLat)
        }
      } else {
        hasLocation.value = false
      }
    }
    
    // 更新地图位置
    const updateMapLocation = (lng, lat) => {
      if (!mapInstance.value || !window.AMap) return
      
      try {
        // 更新地图中心点
        mapInstance.value.setCenter([lng, lat])
        
        // 更新标记点位置
        if (markerInstance.value) {
          markerInstance.value.setPosition([lng, lat])
        }
        
        // 更新信息窗口位置和内容
        if (infoWindowInstance.value) {
          infoWindowInstance.value.setContent(`<h3>${device.value?.name || '设备'}</h3><div>经度: ${lng}<br/>纬度: ${lat}</div>`)
          infoWindowInstance.value.open(mapInstance.value, [lng, lat])
        }
        
        console.log('地图位置已更新:', lng, lat)
      } catch (error) {
        console.error('更新地图位置失败:', error)
      }
    }
    
    // 初始化高德地图
    const initMap = () => {
      // 检查是否已经初始化过地图
      if (mapInstance.value) {
        // 如果地图已初始化，直接更新位置
        updateMapLocation(locationData.value.lng, locationData.value.lat)
        return
      }
      
      // 再次检查地图容器是否存在
      if (!mapContainer.value) {
        console.warn('地图容器未找到或未渲染完成')
        return
      }
      
      // 检查高德地图API是否已加载
      if (window.AMap) {
        try {
          // 创建地图实例并存储
          mapInstance.value = new window.AMap.Map(mapContainer.value, {
            zoom: 16,
            center: [locationData.value.lng, locationData.value.lat],
            resizeEnable: true
          })
          
          // 创建标记点并存储
          markerInstance.value = new window.AMap.Marker({
            position: [locationData.value.lng, locationData.value.lat],
            map: mapInstance.value,
            title: device.value?.name || '设备位置'
          })
          
          // 创建信息窗口并存储
          infoWindowInstance.value = new window.AMap.InfoWindow({
            content: `<h3>${device.value?.name || '设备'}</h3><div>经度: ${locationData.value.lng}<br/>纬度: ${locationData.value.lat}</div>`,
            offset: new window.AMap.Pixel(0, -30)
          })
          infoWindowInstance.value.open(mapInstance.value, [locationData.value.lng, locationData.value.lat])
          
          console.log('地图初始化成功')
        } catch (error) {
          console.error('地图初始化失败:', error)
        }
      } else {
        console.warn('高德地图API未加载，无法显示地图')
        // 动态加载高德地图API
        loadAmapScript().then(() => {
          // 延迟执行，确保API完全加载
          setTimeout(() => {
            initMap()
          }, 100)
        }).catch(error => {
          console.error('加载高德地图API失败:', error)
        })
      }
    }
    
    // 动态加载高德地图脚本
    const loadAmapScript = () => {
      return new Promise((resolve, reject) => {
        const script = document.createElement('script')
        // 这里使用测试key，实际项目中请替换为您自己的key
        script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=8fca2c5f3f865b22917c8f90718d9d3c&callback=initAMap'
        script.onerror = reject
        window.initAMap = () => {
          resolve()
          window.initAMap = null
        }
        document.head.appendChild(script)
      })
    }
    
    // 格式化时间戳
    const formatTimestamp = (timestamp) => {
      if (!timestamp || timestamp === 0) return '-'  
      const date = new Date(timestamp)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }
    
    // 格式化属性值
    const formatPropertyValue = (property) => {
      if (property.value === null) return '-'  
      
      // 针对不同数据类型进行格式化
      switch (property.data_type) {
        case 'bool':
          return property.value === 'true' || property.value === true ? '开启' : '关闭'
        case 'int32':
        case 'float':
        case 'double':
          // 如果是电压，显示为V
          if (property.identifier === 'voltage') {
            return (parseInt(property.value) / 1000).toFixed(2) + 'V'
          }
          return property.value
        default:
          return property.value
      }
    }
    
    // 订阅设备属性变化（SSE）
    const subscribeToDeviceMessages = (deviceId) => {
      // 关闭现有连接
      if (eventSource.value) {
        eventSource.value.close()
      }
      
      try {
        // 使用deviceApi.getDeviceStream创建SSE连接
        eventSource.value = deviceApi.getDeviceStream(deviceId)
        
        // 监听消息
        eventSource.value.onmessage = (event) => {
          try {
            // 忽略心跳消息
            if (event.data.startsWith(':')) return
            
            const message = JSON.parse(event.data)
            console.log('收到设备消息:', message)
            
            // 更新设备属性
            updateDeviceProperty(message)
          } catch (error) {
            console.error('解析设备消息失败:', error)
          }
        }
        
        // 监听错误
        eventSource.value.onerror = (error) => {
          console.error('SSE连接错误:', error)
          isSubscribed.value = false
          
          // 检查是否是401错误，如果是则重定向到登录页
          // 由于EventSource不直接暴露状态码，我们需要检查连接状态
          if (!eventSource.value || eventSource.value.readyState === 2) { // CLOSED状态
            console.log('可能是授权错误，检查是否需要登录')
            // 清除token并重定向到登录页
            localStorage.removeItem('token')
            window.location.hash = '#/login'
            return
          }
          
          // 对于其他错误，尝试重新连接
          setTimeout(() => {
            subscribeToDeviceMessages(deviceId)
          }, 5000)
        }
        
        // 监听连接打开
        eventSource.value.onopen = () => {
          console.log('SSE连接已建立')
          isSubscribed.value = true
        }
        
      } catch (error) {
        console.error('建立SSE连接失败:', error)
        isSubscribed.value = false
      }
    }
    
    // 更新设备属性
    const updateDeviceProperty = (message) => {
      if (!message) return
      
      // 如果消息包含设备状态信息，更新device的status字段
      if (message.status) {
        device.value = {
          ...device.value,
          status: message.status
        }
      }
      
      // 处理设备上下线消息
      if (message.msgType === 'deviceOffline') {
        console.log('设备离线消息:', message)
        device.value = {
          ...device.value,
          status: 'offline'
        }
        ElMessage({ message: '设备已离线', type: 'warning' })
      } else if (message.msgType === 'deviceOnline') {
        console.log('设备上线消息:', message)
        device.value = {
          ...device.value,
          status: 'online'
        }
        ElMessage({ message: '设备已上线', type: 'success' })
      }
      
      // 处理thingProperty类型的消息格式
      if (message.msgType === 'thingProperty' && message.subData && message.subData.params) {
        const params = message.subData.params
        const deviceId = message.subData.deviceId
        const deviceName = message.subData.deviceName
        
        // 遍历params中的所有属性
        Object.keys(params).forEach(paramKey => {
          const param = params[paramKey]
          
          // 查找是否已有该属性
          const existingIndex = deviceProperties.value.findIndex(
            prop => prop.identifier === paramKey
          )
          
          // 创建或更新属性
          // 对于特定的属性（如wifi、命令、上报频率、翻转圈数），设置为可读写
          // 对于其他属性，保留原有access_mode或默认为只读
          const shouldBeReadWrite = (typeof param.value === 'boolean' && paramKey === 'wifi') || 
                                  paramKey === 'cmd' ||
                                  paramKey === 'frequency' || 
                                  paramKey === 'fz_count' ||
                                  paramKey === 'uid' ||
                                  (existingIndex >= 0 && deviceProperties.value[existingIndex].access_mode === '读写');
          
          const updatedProperty = {
            identifier: paramKey,
            name: paramKey, // 使用属性名作为显示名称
            value: param.value,
            data_type: typeof param.value === 'boolean' ? 'bool' : 
                      typeof param.value === 'number' ? 'double' : 'string',
            access_mode: shouldBeReadWrite ? '读写' : 
                        (existingIndex >= 0 ? deviceProperties.value[existingIndex].access_mode : '只读'),
            time: param.time || Date.now(),
            deviceId: deviceId,
            deviceName: deviceName
          }
          
          if (existingIndex >= 0) {
            // 更新现有属性
            deviceProperties.value[existingIndex] = updatedProperty
          } else {
            // 添加新属性
            deviceProperties.value.push(updatedProperty)
          }
          
          // 对于布尔类型，更新boolProperties
          if (updatedProperty.data_type === 'bool') {
            boolProperties[updatedProperty.identifier] = updatedProperty.value
          }
          // 更新editValues
            if (['cmd', 'frequency', 'fz_count','uid'].includes(updatedProperty.identifier)) {
              if (updatedProperty.identifier === 'cmd') {
                // cmd属性保持字符串类型
                editValues[updatedProperty.identifier] = String(updatedProperty.value)
              } else {
                // 数值属性转换为数字类型
                editValues[updatedProperty.identifier] = Number(updatedProperty.value)
              }
            }
          
          // 如果是位置信息，更新位置数据
          if (paramKey === 'lat' || paramKey === 'lng') {
            extractLocationData(deviceProperties.value.reduce((props, prop) => {
              props[prop.identifier] = prop;
              return props;
            }, {}))
          }
        })
      } 
      // 兼容原有格式的消息
      else if (message.identifier) {
        // 查找是否已有该属性
        const existingIndex = deviceProperties.value.findIndex(
          prop => prop.identifier === message.identifier
        )
        
        // 创建或更新属性
        // 对于特定属性（命令、上报频率、翻转圈数、id），确保设置为可读写
        const isSpecialEditableProperty = message.identifier === 'cmd' 
        || message.identifier === 'frequency' 
        || message.identifier === 'fz_count' 
        || message.identifier === 'uid';
        const updatedProperty = {
          identifier: message.identifier,
          name: message.name || message.identifier,
          value: message.value,
          data_type: message.data_type || 'string',
          access_mode: isSpecialEditableProperty ? '读写' : (message.access_mode || '只读'),
          time: message.time || Date.now()
        }
        
        if (existingIndex >= 0) {
          // 更新现有属性
          deviceProperties.value[existingIndex] = updatedProperty
        } else {
          // 添加新属性
          deviceProperties.value.push(updatedProperty)
        }
        
        // 对于布尔类型，更新boolProperties
        if (updatedProperty.data_type === 'bool' && updatedProperty.access_mode === '读写') {
          boolProperties[updatedProperty.identifier] = updatedProperty.value === 'true' || updatedProperty.value === true
        }
        // 更新editValues
          if (['cmd', 'frequency', 'fz_count','uid'].includes(updatedProperty.identifier)) {
            if (updatedProperty.identifier === 'cmd') {
              // cmd属性保持字符串类型
              editValues[updatedProperty.identifier] = String(updatedProperty.value)
            } else {
              // 数值属性转换为数字类型
              editValues[updatedProperty.identifier] = Number(updatedProperty.value)
            }
          }
        
        // 如果是位置信息，更新位置数据
        if (message.identifier === 'lat' || message.identifier === 'lng') {
          extractLocationData(deviceProperties.value.reduce((props, prop) => {
            props[prop.identifier] = prop;
            return props;
          }, {}))
        }
      }
    }
    
    // 处理布尔属性开关变化
    const handleBoolChange = async (identifier, value) => {
      try {
        const deviceId = props.id || route.params.id
        await deviceApi.updateDeviceProperty(deviceId, { key: identifier, value })
        ElMessage.success('属性更新成功')
      } catch (error) {
        console.error('更新属性失败:', error)
        ElMessage.error('属性更新失败')
        // 恢复原始值
        boolProperties[identifier] = !value
      }
    }
    
    // 处理字符串属性变化
    const handleStringChange = async (identifier, value) => {
      try {
        const deviceId = props.id || route.params.id
        await deviceApi.updateDeviceProperty(deviceId, { key: identifier, value })
        ElMessage.success('属性更新成功')
      } catch (error) {
        console.error('属性更新失败:', error)
        ElMessage.error('属性更新失败')
      }
    }

    // 处理数值属性变化
    const handleNumberChange = async (identifier, value) => {
      try {
        const deviceId = props.id || route.params.id
        await deviceApi.updateDeviceProperty(deviceId, { key: identifier, value })
        ElMessage.success('属性更新成功')
      } catch (error) {
        console.error('属性更新失败:', error)
        ElMessage.error('属性更新失败')
      }
    }
    
    // 执行命令
    const executeCommand = async () => {
      if (!commandForm.key) {
        ElMessage.warning('请选择要执行的命令')
        return
      }
      
      try {
        executingCommand.value = true
        const deviceId = props.id || route.params.id
        const response = await deviceApi.executeCommand(deviceId, {
          key: "cmd",
          value: `env:${commandForm.key}=${commandForm.value}`
        })
        
        if (response.status === 200) {
          ElMessage.success('命令执行成功')
          // 清空表单
          commandForm.key = ''
          commandForm.value = ''
          
          // 重新加载设备属性以更新显示
          await loadDeviceProperties(deviceId)
        }
      } catch (error) {
        console.error('执行命令失败:', error)
        // 显示更详细的错误信息，包括response.data中的内容
        const errorMsg = error.response?.data?.msg || error.response?.data || '执行命令失败'
        ElMessage.error(`执行命令失败: ${errorMsg}`)
      } finally {
        executingCommand.value = false
      }
    }

    // 执行命令
    const fota = async () => {
      try {
        executingCommand.value = true
        const deviceId = props.id || route.params.id
        const response = await deviceApi.executeCommand(deviceId, {
          key: "cmd",
          value: `FOTA||http://app.towerfly.cn/qpy/Onemqtt.py||/usr/Onemqtt.py`
        })
        
        if (response.status === 200) {
          ElMessage.success('命令执行成功')
          // 重新加载设备属性以更新显示
          await loadDeviceProperties(deviceId)
        }
      } catch (error) {
        console.error('执行命令失败:', error)
        // 显示更详细的错误信息，包括response.data中的内容
        const errorMsg = error.response?.data?.msg || error.response?.data || '执行命令失败'
        ElMessage.error(`执行命令失败: ${errorMsg}`)
      } finally {
        executingCommand.value = false
      }
    }
    
    // 返回列表
    const handleBack = () => {
      router.push('/')
    }
    
    // 监听路由参数变化
    watch(() => route.params.id, (newId, oldId) => {
      loadDeviceDetail()
      
      // 如果设备ID变化，重新订阅
      if (newId && newId !== oldId) {
        subscribeToDeviceMessages(newId)
      }
    })
    
    // 监听hasLocation变化，当有位置数据时尝试初始化地图
    watch(hasLocation, (newValue) => {
      if (newValue) {
        nextTick(() => {
          if (mapContainer.value && !window.mapInitialized) {
            initMap()
          }
        })
      }
    })
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadDeviceDetail()
      
      // 组件完全挂载后再尝试一次地图初始化
      setTimeout(() => {
        if (hasLocation.value && mapContainer.value) {
          initMap()
        }
      }, 500)
      
      // 开始订阅设备消息
      const deviceId = props.id || route.params.id
      if (deviceId) {
        subscribeToDeviceMessages(deviceId)
      }
    })
    
    // 组件卸载时关闭SSE连接
    onUnmounted(() => {
      if (eventSource.value) {
        eventSource.value.close()
        eventSource.value = null
      }
    })
    
    return {
      device,
      deviceProperties,
      loading,
      executingCommand,
      commandForm,
      executeCommand,
      fota,
      handleBack,
      videoUrl,
      mapContainer,
      boolProperties,
      editValues,
      hasLocation,
      isSubscribed,
      formatTimestamp,
      formatPropertyValue,
      handleBoolChange,
      handleStringChange,
      handleNumberChange
    }
  }
}
</script>

<style scoped>
.device-detail-container {
  padding: 10px;
  /* 适配手机屏幕的响应式容器 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.device-info {
  margin-top: 15px;
}

.properties-section,
.control-section,
.map-section,
.video-section {
  margin-top: 20px;
}

.properties-section h3,
.control-section h3,
.map-section h3,
.video-section h3 {
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: bold;
}

/* 表格滚动容器，适配小屏幕 */
:deep(.el-table) {
  overflow-x: auto;
  display: block;
}

/* 确保表格内容不被截断 */
:deep(.el-table__body-wrapper) {
  overflow-x: auto;
  min-height: 0;
}

.map-container {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  overflow: hidden;
  /* 在小屏幕上减少地图高度 */
}

.video-player {
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.loading-state {
  position: relative;
  min-height: 200px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.error-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

/* 响应式样式，适配不同屏幕尺寸 */
@media (max-width: 768px) {
  .device-detail-container {
    padding: 8px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .card-header .el-button {
    width: 100%;
  }
  
  /* 调整地图和视频在小屏幕上的高度 */
  .map-container {
    height: 250px !important;
  }
  
  .video-player {
    max-height: 250px !important;
  }
  
  /* 调整表单元素在小屏幕上的显示 */
  :deep(.el-form-item__content) {
    width: 100%;
  }
  
  /* 确保表格在小屏幕上可以水平滚动 */
  .properties-section {
    overflow-x: auto;
  }
  
  /* 调整描述组件在小屏幕上的显示 */
  :deep(.el-descriptions) {
    min-width: 100%;
  }
}

@media (max-width: 480px) {
  .map-container {
    height: 200px !important;
  }
  
  .video-player {
    max-height: 200px !important;
  }
  
  .properties-section h3,
  .control-section h3,
  .map-section h3,
  .video-section h3 {
    font-size: 14px;
  }
  
  /* 调整表格列宽，确保在小屏幕上显示更友好 */
  :deep(.el-table-column) {
    min-width: 80px;
  }
}
</style>